<?php

namespace App\Models\Applet\User;

use App\Helpers\MvcHelper;

class UserAddressModel extends BaseUserModel
{
    protected $table = 'user_address';

    const IS_DEFAULT_NO  = 0; // 非默认
    const IS_DEFAULT_YES = 1; // 默认

    /**
     * 我的地址列表
     * @param string[] $fields
     * @return array
     */
    public function list(array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        return $this->select($fields)
                    ->where('user_id', MvcHelper::getLoginUserId())
                    ->where('deleted', self::DELETED_NO)
                    ->orderBy('id', 'desc')
                    ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
                    ->limit(PAGE_SIZE)
                    ->get()
                    ->toArray();
    }

    /**
     * 根据用户id查询地址信息
     * @param int $userId
     * @param array $fields
     * @return array
     */
    public function getItemByUserId(int $userId, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $result = $this->select($fields)
                       ->where('user_id', $userId)
                       ->where('deleted', self::DELETED_NO)
                       ->first();
        return $result ? $result->toArray() : [];
    }

    /**
     * 根据用户id和主键id查询
     * @param int $userId
     * @param int $id
     * @param array $fields
     * @return array
     */
    public function getItemByUserIdAndId(int $userId, int $id, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $result = $this->select($fields)
                       ->where('id', $id)
                       ->where('user_id', $userId)
                       ->where('deleted', self::DELETED_NO)
                       ->first();
        return $result ? $result->toArray() : [];
    }

    /**
     * 根据用户id将其他的默认状态改为取消默认
     * @return void
     */
    public function updateIsDefaultNoByUserId(int $userId)
    {
        $this->where('user_id', $userId)
             ->where('is_default', self::IS_DEFAULT_YES)
             ->where('deleted', self::DELETED_NO)
             ->update([
                 'is_default' => self::IS_DEFAULT_NO,
             ]);
    }
}
